<template>
  <div>
    <div class="app-container">
      <!-- 顶部标题区（不改动搜索逻辑，仅样式包装） -->
      <div class="flex items-center justify-between mb-20px">
        <div>
          <h1 class="text-22px font-600 text-#1f2329">应用管理</h1>
          <p class="text-13px text-#646A73 mt-6px">管理您的开发工具应用和相关配置</p>
        </div>
        <div class="flex items-center gap-12px">
          <el-button icon="QuestionFilled" @click="helpVisible = true">帮助</el-button>
          <el-button type="primary" icon="Plus" @click="handleGetForm(0)">新建应用</el-button>
        </div>
      </div>

      <!-- 原搜索表单，保持字段与逻辑不变，仅外层视觉样式 -->
      <div class="rounded-8px border border-#ebeef5 bg-white px-16px mb">
        <div class="search">
          <el-form ref="form" :model="searchData" label-width="80px" class="pt-20px" :inline="true" label-position="left">
            <el-form-item label="搜索">
              <el-input v-model="searchData['title like']" placeholder="请输入应用名称" />
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="searchData['name']" placeholder="应用标识" class="w-100px" />
            </el-form-item>
            <el-form-item style="text-align: right; margin-right: 20px">
              <el-button type="primary" @click="handleGetList(0)">筛选</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 卡片列表 -->
      <div v-loading="loading" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-4">
        <div
          v-for="item in dkTableData"
          :key="item.id"
          class="card shadow-sm hover:shadow-md transition-all duration-200 cursor-pointer"
          @click="handleCardClick(item)"
        >
          <!-- 卡片头部：图标、状态、标题/描述、标识与ID -->
          <div class="card-header !mb0 !pb5 relative">
            <div class="gap-12px">
              <div class="flex items-center gap-12px mb">
                <div class="w-48px h-48px rounded-12px flex items-center justify-center">
                  <img
                    :src="item.icon || '/src/assets/default/addon.png'"
                    :alt="item.title"
                    class="w-48px h-48px object-contain rounded-12px"
                    @error="handleImageError"
                  />
                </div>
                <div>
                  <p class="text-13px">
                    <span class="text-#86909C mr-8px">应用ID:</span>
                    <span class="text-#1D2129">{{ item.id }}</span>
                  </p>
                  <p class="text-13px">
                    <span class="text-#86909C mr-8px">标识:</span>
                    <span class="text-#1D2129">{{ item.name }}</span>
                  </p>
                </div>
              </div>
              <div class="flex-1 min-w-0">
                <h3 class="text-18px font-600 text-#0052D9 mb-2px truncate">{{ item.title }}</h3>
                <p class="text-12px leading-20px text-#4E5969 break-words line-clamp-1">{{ item.desc }}</p>
              </div>
            </div>
          </div>

          <!-- 卡片操作：图标 + 文本 -->
          <div :class="isCrudMode ? 'grid grid-cols-2 gap-1 text-center select-none' : 'grid grid-cols-3 gap-1 text-center select-none'">
            <div
              class="flex flex-col items-center gap-6px cursor-pointer rounded-6px p-2 transition-all duration-200 hover:bg-#F5F7FA hover:text-#0052D9 hover:shadow-sm"
              @click.stop="showCrud(item)"
            >
              <dk-icon icon="mdi-light:table" class="text-24px text-#4E5969" />
              <span class="text-13px text-#4E5969">数据表</span>
            </div>
            <div
              class="flex flex-col items-center gap-6px cursor-pointer rounded-6px p-2 transition-all duration-200 hover:bg-#F5F7FA hover:text-#0052D9 hover:shadow-sm"
              @click.stop="router.push('/crud/' + item.id)"
            >
              <dk-icon icon="tabler:layout-grid" class="text-24px text-#4E5969" />
              <span class="text-13px text-#4E5969">新CRUD</span>
            </div>
            <!-- 版本按钮 - 仅在非CRUD模式下显示 -->
            <div
              v-if="!isCrudMode"
              class="flex flex-col items-center gap-6px cursor-pointer rounded-6px p-2 transition-all duration-200 hover:bg-#F5F7FA hover:text-#0052D9 hover:shadow-sm"
              @click.stop="router.push('/addons/version/' + item.id)"
            >
              <dk-icon icon="tabler:git-branch" class="text-24px text-#4E5969" />
              <span class="text-13px text-#4E5969">版本</span>
            </div>
            <!-- SQL按钮 - 仅在非CRUD模式下显示 -->
            <div
              v-if="!isCrudMode"
              class="flex flex-col items-center gap-6px cursor-pointer rounded-6px p-2 transition-all duration-200 hover:bg-#F5F7FA hover:text-#0052D9 hover:shadow-sm"
              @click.stop="showUpgradeSql(item)"
            >
              <dk-icon icon="tabler:database" class="text-24px text-#4E5969" />
              <span class="text-13px text-#4E5969">SQL</span>
            </div>
            <!-- 编辑按钮 - 仅在非CRUD模式下显示 -->
            <div
              v-if="!isCrudMode"
              class="flex flex-col items-center gap-6px cursor-pointer rounded-6px p-2 transition-all duration-200 hover:bg-#F5F7FA hover:text-#0052D9 hover:shadow-sm"
              @click.stop="handleGetForm(item.id)"
            >
              <dk-icon icon="tabler:edit" class="text-24px text-#4E5969" />
              <span class="text-13px text-#4E5969">编辑</span>
            </div>
            <!-- 删除按钮 - 仅在非CRUD模式下显示 -->
            <div v-if="!isCrudMode" class="flex flex-col items-center gap-6px text-#4E5969 opacity-50 p-2 cursor-not-allowed">
              <dk-icon icon="tabler:trash" class="text-24px" />
              <span class="text-13px">删除</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && dkTableData.length === 0" class="text-center py-12">
        <div class="text-gray-400 text-lg mb-4">
          <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
            ></path>
          </svg>
        </div>
        <p class="text-gray-500 text-lg">暂无应用数据</p>
        <p class="text-gray-400 text-sm mt-2">点击"新增"按钮创建第一个应用</p>
      </div>
      <!-- 分页 -->
      <div v-if="total > 0" class="flex justify-center mt-6">
        <el-pagination
          background
          layout="total, prev, pager, next, sizes"
          :total="total"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="currentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <dk-form ref="fc" :form-data="formData" :is-dialog="true" @submit="handleGetList(0)" />
    <el-dialog v-model="dialogUpgradeSql" title="更新SQL" width="1200px">
      <upgrade-sql-edit :key="chooseId" :aid="chooseId" @success="dialogUpgradeSql = false" />
    </el-dialog>
    <el-dialog v-model="dialogCrudVisible" title="数据表列表" width="1200px">
      <crud-list v-if="chooseId && dialogCrudVisible" :key="chooseId" :aid="chooseId" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { del, getList as apiGetList, getForm as apiGetForm } from '@/api/addons/addon.js'
import UpgradeSqlEdit from '@/views/addons/addon/components/UpgradeSqlEdit.vue'
import CrudList from '@/views/crud/components/crudList.vue'

defineOptions({
  name: 'AddonList'
})

defineProps<{
  value?: string
}>()

const route = useRoute()
const router = useRouter()

// 检测是否为CRUD模式
const isCrudMode = computed(() => {
  return route.query.crud === '1'
})

// 响应式数据
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const dkTableData = ref<any[]>([])
const searchData = ref<any>({})
const dialogFormVisible = ref(false)
const formWidth = ref('1000px')
const formData = ref<any>(null)
const loading = ref(true)
const detail = ref<any>({})
const dialogVisible = ref(false)
const dialogUpgradeSql = ref(false)
const chooseId = ref(0)
const helpVisible = ref(false)
const dialogCrudVisible = ref(false)

// 模板引用
const fc = ref<any>(null)

// 方法
const showUpgradeSql = (row: any) => {
  chooseId.value = row.id
  dialogUpgradeSql.value = true
}

const showCrud = (row: any) => {
  chooseId.value = row.id
  dialogCrudVisible.value = true
}

const handleGetForm = (id: number) => {
  apiGetForm(id).then((res: any) => {
    formData.value = res.data
    // fc.value.dialogFormVisible = true
    fc.value.show()
  })
}

const handleDelete = (item: any) => {
  ElMessageBox.confirm('此操作将永久删除该事件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    del(item.id).then(() => {
      ElMessage.success('删除成功!')
      handleGetList(0)
    })
  })
}

const handleGetList = (pageNum?: number) => {
  page.value = pageNum || 0
  apiGetList(page.value, pageSize.value, searchData.value).then((res: any) => {
    console.log(res)
    dkTableData.value = res.data
    total.value = parseInt(res.msg)
    loading.value = false
  })
}

const reset = () => {
  searchData.value = {
    name: '',
    type: ''
  }
  handleGetList()
}

const currentChange = (pageNum: number) => {
  handleGetList(pageNum)
}

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  handleGetList(1) // 重置到第一页
}

// 处理卡片点击
const handleCardClick = (item: any) => {
  // 可以在这里添加卡片点击的逻辑，比如跳转到详情页
  console.log('Card clicked:', item)
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = '/src/assets/default/addon.png'
}

onMounted(() => {
  reset()
})
</script>

<style scoped>
/* UnoCSS 已经提供了所需的样式，这里可以添加自定义样式 */
</style>
